# -*- coding: utf-8 -*-



from settings import ydm_appid, ydm_appkey, ydm_password, ydm_username

# YDMApi = windll.LoadLibrary('yundamaAPI-x64')


# class Ydm():
#     ydm_appid = ydm_appid
#     ydm_appkey = ydm_appkey
#     ydm_username = ydm_username
#     ydm_password = ydm_password
#
#     # code_type = 1004
#     #
#     # # 例：1004表示4位字母数字，不同类型收费不同。请准确填写，否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
#     # codetype = 1004
#     #
#     # # 分配30个字节存放识别结果
#     # result = c_char_p(b"                              ")
#     #
#     # # 识别超时时间 单位：秒
#     # timeout = 60
#
#
#     def get_code(self, filename=None):
#
#         if not filename:
#             raise Exception('img_path can not be empty!!!')
#
#         # captchaId = YDMApi.YDM_EasyDecodeByPath(self.ydm_username, self.ydm_password,
#         #                                         self.ydm_appid, self.ydm_appkey, filename, self.codetype,
#         #                                         self.timeout, self.result)
#         # 第一步：初始化云打码，只需调用一次即可
#         YDMApi.YDM_SetAppInfo(self.ydm_appid, self.ydm_appkey)
#
#         # 第二步：登陆云打码账号，只需调用一次即可
#         uid = YDMApi.YDM_Login(self.ydm_username, self.ydm_password)
#
#         # 例：1004表示4位字母数字，不同类型收费不同。请准确填写，否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
#         codetype = 1004
#
#         # 分配30个字节存放识别结果
#         result = c_char_p(b"                              ")
#
#         if uid < 0:
#             print('登陆失败，错误代码：%d' % uid)
#             return {}
#         # 开始识别
#
#         balance = YDMApi.YDM_GetBalance(self.ydm_username, self.ydm_password)
#
#         print('登陆成功，用户名：%s，剩余题分：%d' % (self.ydm_username, balance))
#
#
#         # 普通识别函数，需先调用 YDM_SetAppInfo 和 YDM_Login 初始化
#         captchaId = YDMApi.YDM_DecodeByPath(filename, codetype, result)
#
#         # print("普通识别：验证码ID：%d，识别结果：%s" % (captchaId, result.value))
#
#         # print('{}\n{}'.format(self.ydm_username, ydm_password))
#
#         result = {'code_id': captchaId, 'code_value': result.value}
#
#         return result

import json, time, requests
import http.client, mimetypes, urllib

######################################################################

# YDMHttp, image_decode 在 http://www.seotest.cn/jishu/46835.html

class YDMHttp:
    apiurl = 'http://api.yundama.com/api.php'
    username = ydm_username
    password = ydm_password
    appid = ydm_appid
    appkey = ydm_appkey

    def __init__(self, username, password, appid, appkey):
        self.username = username
        self.password = password
        self.appid = str(appid)
        self.appkey = appkey

    def request(self, fields, files=[]):
        response = self.post_url(self.apiurl, fields, files)
        response = json.loads(response)
        return response

    def balance(self):
        data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['balance']
        else:
            return -9001

    def login(self):
        data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['uid']
        else:
            return -9001

    def upload(self, filename, codetype, timeout):
        data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
        file = {'file': filename}
        response = self.request(data, file)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['cid']
        else:
            return -9001

    def result(self, cid):
        data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey, 'cid': str(cid)}
        response = self.request(data)
        return response and response['text'] or ''

    def decode(self, filename, codetype, timeout):
        cid = self.upload(filename, codetype, timeout)
        if (cid > 0):
            for i in range(0, timeout):
                result = self.result(cid)
                if (result != ''):
                    return cid, result
                else:
                    time.sleep(1)
            return -3003, ''
        else:
            return cid, ''

    def report(self, cid):
        data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey, 'cid': str(cid), 'flag': '0'}
        response = self.request(data)
        if (response):
            return response['ret']
        else:
            return -9001

    def post_url(self, url, fields, files=[]):
        for key in files:
            files[key] = open(files[key], 'rb')
        res = requests.post(url, files=files, data=fields)
        return res.text


######################################################################

# 用户名
username = '注册的用户账号'

# 密码
password = '账号密码'

# 软件ＩＤ，开发者分成必要参数。登录开发者后台【我的软件】获得！
appid = 4999  # 对应的在平台中创建的软件id

# 软件密钥，开发者分成必要参数。登录开发者后台【我的软件】获得！
appkey = '需要在云打码平台中创建获取'

# 超时时间，秒
timeout = 30

# 封装调用接口--image_decode()

# 例：1004表示4位字母数字，不同类型收费不同。请准确填写，否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html

def image_decode(filename, codetype=1004):
    # 检查
    if (username == 'username'):
        print('请设置好相关参数再测试')
    else:
        # 初始化
        yundama = YDMHttp(username=ydm_username, password=ydm_password, appid=ydm_appid, appkey=ydm_appkey)

        # 登陆云打码
        uid = yundama.login()
        print('uid: %s' % uid)

        # 查询余额
        balance = yundama.balance()
        print('balance: %s' % balance)

        # 开始识别，图片路径，验证码类型ID，超时时间（秒），识别结果
        cid, result = yundama.decode(filename, codetype, timeout)
        print('cid: %s, result: %s' % (cid, result))
        return {'cid': cid, 'result': result}

img_path = 'E:/graph_validate_code_test/images/validate_code/2019-11-25 13-14-28_validate_code_img.png'

######################################################################
#
if __name__ == '__main__':
    result = image_decode(img_path)
    print(result)